#include"sendF.h"
#include<errno.h>
#include"network.h"
#include"proto.h"
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/stat.h>

/*
 * Function aims to send file to a given sock
 * Data is taken from the given FILE* and start from long start.
 */
void sendFileSeg(int sock, FILE* fin, long offset, size_t len)
{
	char buf[BUFF_SIZE];
	size_t sendLen = 0;
	fseek(fin, offset, SEEK_SET);
	printf("Transmitting new file...");

	while (sendLen < len)
	{
		size_t lastReadLen = fread(buf, 1, BUFF_SIZE, fin);
		size_t lastSendLen = send(sock, buf, lastReadLen, 0);
		printf("%d send\n",lastSendLen);

		//a slick is not send completely
		if (lastSendLen != lastReadLen)
		{
			sendLen += lastSendLen;
			fseek(fin, sendLen, SEEK_SET);
			continue;
		}
		
		//when last slick was just send
		if (lastReadLen != BUFF_SIZE)
			break;

		sendLen += lastSendLen;
		sleep(1);
	}
}

int getFileLen(char* filename)
{
	struct stat fst;
	if (stat(filename, &fst))
	{
		perror("ERROR!!:");
		return -1;
	}
	printf("Get file length from %s %ldB\n", filename, fst.st_size);
	return fst.st_size;
}
